package com.gxuwz.medical.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.gxuwz.medical.database.DbUtil;
import com.gxuwz.medical.domain.area.Area;
import com.gxuwz.medical.domain.vo.Page;

import com.gxuwz.medical.exception.DbException;

public class AreaDao extends GenericDao<Area> {

	@Override
	protected Area handle(ResultSet rs) throws SQLException {
		try {
			Area model = new Area();
			model.setAreacode(rs.getString("areacode"));
			model.setAreaname(rs.getString("areaname"));
			model.setGrade(rs.getInt("grade"));
			return model;
		} catch (SQLException e) {

			throw new SQLException("结果集转为实例失败!", e);
		}
	}

	/**
	 * 分页
	 * 
	 * @param sql
	 * @param params
	 * @param page
	 * @param size
	 * @return
	 * @throws SQLException
	 */

	public Page queryOjectsByPage(String sql, Object[] params, int pageNo,
			int size) throws SQLException {
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		Page page = null;
		List<Area> areas = new ArrayList<Area>();
		try {
			int start = (pageNo - 1) * size;
			conn = DbUtil.getConn();
			pstmt = conn.prepareStatement(sql + " limit " + start + "," + size);
			int index = 1;
			if (params != null) {
				for (Object param : params) {
					if (param instanceof String) {
						pstmt.setString(index++, (String) param);
					}
					if (param instanceof Integer) {
						pstmt.setInt(index++, (Integer) param);
					}
					if (param instanceof Float) {
						pstmt.setFloat(index++, (Float) param);
					}
				}
			}
			rs = pstmt.executeQuery();
			while (rs.next()) {
				Area a = handle(rs);
				areas.add(a);
			}
			// 统计SQL对应记录数
			int total = count(sql, params);
			page = new Page(total, pageNo, size, areas);
			return page;
		} catch (SQLException e) {
			throw new SQLException("执行SQL[" + sql + "]失败", e);
		}
	}

	/**
	 * 按级别查找行政区域列表
	 * 
	 * @param grades
	 * @return
	 * @throws DbException
	 */
	public List<Area> findListByGrade(int[] grades) throws DbException {
		try {
			String sql = "select * from t_area where 1=1";
			if (grades != null) {
				String grade = "(1";
				for (int g : grades) {
					grade = grade + "," + g;
				}
				grade += ")";
				sql += " and grade in " + grade;
			}
			Object[] params = {};

			return super.queryOjects(sql, params);
		} catch (SQLException e) {
			throw new DbException("按级别查找行政区域失败!", e);
		}
	}
	
	public List<Area>findChildArea(String areacode,int grade)throws DbException{
		try{
	    String sql="select * from t_area where areacode like'"+areacode+"%' and grade="+grade;
		  Object[]params={};
		  return super.queryOjects(sql, params);
		}catch(SQLException e){
			e.printStackTrace();
			throw new DbException("查找所有子一级行政区域失败",e);
		}
	}
	

}
